package top.jinlijun.heytea.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.jinlijun.heytea.entities.*;
import top.jinlijun.heytea.service.ICommodityService;
import top.jinlijun.heytea.service.ILoginService;
import top.jinlijun.heytea.service.IOrderService;
import top.jinlijun.heytea.service.IStoreService;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/commodity")
public class MCommodityController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ICommodityService commodityService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IStoreService storeService;

    @Autowired
    private ILoginService loginService;

    @RequestMapping("/addAllCommodity")
    public RetResult addAllCommodity(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam("file") MultipartFile file, String formData) throws IOException {
        System.out.println(formData);
        JSONObject parse = JSONObject.parseObject(formData);


        String imgUrl;
        String path = ResourceUtils.getURL("classpath:").getPath()+"static/images/";
        String realPath = path.replace('/', '\\').substring(1,path.length());

        String fileName = file.getOriginalFilename();
        System.out.println("fileName:" + fileName);
        //方法返回的图片url 如："http://127.0.0.1:8080/upload/imgs/logo.jpg.png"
        String url = "";
        if (Objects.isNull(file) || file.isEmpty()) {
            System.out.println("文件为空");
        }
        try {
            url = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + request.getContextPath() + "/static/images/";
            //写入目的地
            FileUtils.writeByteArrayToFile(new File(realPath + fileName),
                    file.getBytes());
        } catch (Exception e) {
            System.out.println("error");
        }
        System.out.println(url + fileName);
        imgUrl = url + fileName;
//        System.out.println(parse.getString("commodityName"));
//        System.out.println(parse.getString("tags"));
//        System.out.println(parse.getString("typeId"));
//        System.out.println(parse.getString("isAttribute"));
//        System.out.println(parse.getString("desc"));
//        System.out.println(parse.getString("characteristic"));
//        System.out.println(parse.getString("price"));
//        System.out.println(parse.getString("attributeIds"));
//        System.out.println(parse.getString("attributeList"));
        Commodity commodity;
        if (parse.getString("isAttribute")=="true") {
            commodity = new Commodity(imgUrl, parse.getString("commodityName"), parse.getString("tags"), Integer.parseInt(parse.getString("typeId")), parse.getString("desc"), parse.getString("characteristic"), Float.parseFloat(parse.getString("price")), 1,parse.getString("attributeIds"));
        } else {
            commodity = new Commodity(imgUrl, parse.getString("commodityName"), parse.getString("tags"), Integer.parseInt(parse.getString("typeId")), parse.getString("desc"), parse.getString("characteristic"), Float.parseFloat(parse.getString("price")),0,parse.getString("attributeIds"));
        }
        System.out.println(commodity.toString());
        commodityService.insertCommodity(commodity);
        return RetResponse.makeOKRsp();
    }

    @RequestMapping("/getAllAttributes")
    public RetResult getAllAttributes() {
        List<Attribute> attributes = commodityService.getAttributes();
        return RetResponse.makeOKRsp(attributes);
    }

    @RequestMapping("/getAllCommodityTypes")
    public RetResult getAllCommodityTypes() {
        List<CommodityType> types = commodityService.getAllCommodityTypes();
        return RetResponse.makeOKRsp(types);
    }

    @RequestMapping("/addCommodityType")
    public RetResult addCommodityType(String typeName) {
        System.out.println(typeName);
        CommodityType commodityType = new CommodityType(typeName);
        commodityService.addCommodityType(commodityType);
        return RetResponse.makeOKRsp();
    }

    @RequestMapping("/deleteCommodityType")
    public RetResult deleteCommodityType(String typeId,String typeName) {
        CommodityType commodityType = new CommodityType(Integer.parseInt(typeId),typeName);
        commodityService.deleteCommodityType(commodityType);
        return RetResponse.makeOKRsp();
    }

    @RequestMapping("/updateCommodityType")
    public RetResult updateCommodityType(String typeId,String typeName) {
        CommodityType commodityType = new CommodityType(Integer.parseInt(typeId),typeName);
        commodityService.updateCommodityType(commodityType);
        return RetResponse.makeOKRsp();
    }

    @RequestMapping("/MGetCommodities")
    public RetResult getAllCommodities() {
        List<Commodity> commodities = commodityService.getCommodities();
        return RetResponse.makeOKRsp(commodities);
    }

    @RequestMapping("/MGetOrders")
    public RetResult MGetOrders() {
        List<Order> currentOrder = orderService.getCurrentOrder();
        List<Order> cancelOrder = orderService.getCancelOrder();
        List<Order> finishOrder = orderService.getFinishOrder();
        List<Order> waitPayOrder = orderService.getWaitPayOrder();
        for (Order order : currentOrder) {
            List<Commodity> commodities = orderService.getCommodityByOrder(order);
            order.setCommodityList(commodities);
            User user = new User();
            user.setUserId(order.getUserId());
            order.setUser(loginService.findUserById(user));
            order.setStore(storeService.getStoreById(order.getStoreId()));
        }
        for (Order order : cancelOrder) {
            List<Commodity> commodities = orderService.getCommodityByOrder(order);
            order.setCommodityList(commodities);
            User user = new User();
            user.setUserId(order.getUserId());
            order.setUser(loginService.findUserById(user));
            order.setStore(storeService.getStoreById(order.getStoreId()));
        }
        for (Order order : finishOrder) {
            List<Commodity> commodities = orderService.getCommodityByOrder(order);
            order.setCommodityList(commodities);
            User user = new User();
            user.setUserId(order.getUserId());
            order.setUser(loginService.findUserById(user));
            order.setStore(storeService.getStoreById(order.getStoreId()));
        }
        for (Order order : waitPayOrder) {
            List<Commodity> commodities = orderService.getCommodityByOrder(order);
            order.setCommodityList(commodities);
            User user = new User();
            user.setUserId(order.getUserId());
            order.setUser(loginService.findUserById(user));
            order.setStore(storeService.getStoreById(order.getStoreId()));
        }
        LinkedHashMap<String, List<Order>> map = new LinkedHashMap<String, List<Order>>();
        map.put("currentOrder",currentOrder);
        map.put("cancelOrder",cancelOrder);
        map.put("finishOrder",finishOrder);
        map.put("waitPayOrder",waitPayOrder);
        return RetResponse.makeOKRsp(map);
    }

    @RequestMapping("/MChangeOrderToComplate")
    public RetResult MChangeOrderToComplate(Order order) {
        orderService.changeOrderToComplate(order);
        return RetResponse.makeOKRsp();
    }

}
